<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
  </head>
  <style>
    input {
      width: 80%;
      padding: 8px;
    }
  </style>
  <body>
    <input type="text" placeholder="请输入内容" onkeyup="saveHandle(event)" />
    <hr />
    <h1>这是一个dome</h1>
    <ul id="list"></ul>
    <script src="./js/main.js"></script>
    <script>
      function loadData() {
        //"/api/v1/people" 同端口下不用写网址
        axios.get("/api/v1/people").then((res) => {
          console.log(res.data);
          var strHtml = "";
          res.data.forEach((item) => {
            strHtml += ` <li>${item.name}</li>`;
          });
          document.querySelector("#list").innerHTML = strHtml;
        });
      }

      function saveHandle(e) {
        //keyCode 表示按键码，最重要的是13 = 回车
        // currentTarget 表示绑定事件的标签
        // target 表示触发事件的标签
        if (e.keyCode === 13) {
          // console.log(e.keyCode);
          if (e.currentTarget.value) {
            //如果输入框有值
            axios
              .post("/api/v1/people", {
                name: e.currentTarget.value,
              })
              .then(() => {
                loadData();
              });
            e.currentTarget.value = "";
          } else {
            alert("请输入内容");
          }
        }
      }
      loadData();
    </script>
  </body>
</html>
